package by.dkusch.aircompany.webapp.page.users.panel;

import javax.inject.Inject;

import org.apache.wicket.Page;
import org.apache.wicket.bean.validation.PropertyValidator;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow.PageCreator;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.form.validation.EqualPasswordInputValidator;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.validation.validator.EmailAddressValidator;
import org.apache.wicket.validation.validator.PatternValidator;

import by.dkusch.aircompany.model.tables.UserAccount_;
import by.dkusch.aircompany.model.tables.UserProfile;
import by.dkusch.aircompany.model.tables.UserProfile_;
import by.dkusch.aircompany.services.UserService;
import by.dkusch.aircompany.webapp.app.BasicAuthenticationSession;
import by.dkusch.aircompany.webapp.page.base.enums.ActionType;
import by.dkusch.aircompany.webapp.page.base.validator.UniqueFieldValidator;
import by.dkusch.aircompany.webapp.page.base.validator.UniqueUserEmailValidator;
import by.dkusch.aircompany.webapp.page.main.HomePage;
import by.dkusch.aircompany.webapp.page.users.entity.UserProfileModel;

public class ProfileEditPanel extends Panel {

	private static final long serialVersionUID = 1L;
	@Inject
	private UserService userService;
	private final String PASSWORD_PATTERN = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})";
	private final String PASSWORD_PATTERN_1 = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])";
	private final String PASSWORD_PATTERN_2 = "((?=.*\\d)(?=.*[a-z,A-Z]).{6,20})";

	public ProfileEditPanel(String id, final UserProfile profile, final PageCreator pageCreator, ActionType action) {
		super(id);
		final boolean isNew = (profile.getId() == null);
		final boolean isDba = BasicAuthenticationSession.get().isUserDba();

		final UserProfileModel profileModel = new UserProfileModel(profile);
		Form<UserProfileModel> form = new Form<UserProfileModel>("form", new CompoundPropertyModel<UserProfileModel>(profileModel));

		final TextField<String> tfFirstName = new TextField<String>("profile.firstName");
		tfFirstName.add(new PropertyValidator<String>()).setLabel(new ResourceModel("user.list.name.first"));
		form.add(tfFirstName);

		final TextField<String> tfSecondName = new TextField<String>("profile.secondName");
		tfSecondName.add(new PropertyValidator<String>()).setLabel(new ResourceModel("user.list.name.second"));
		form.add(tfSecondName);

		final TextField<String> tfLastName = new TextField<String>("profile.lastName");
		tfLastName.add(new PropertyValidator<String>()).setLabel(new ResourceModel("user.list.name.last"));
		form.add(tfLastName);

		final CheckBox chBArc = new CheckBox("profile.arcFl");
		chBArc.add(new PropertyValidator<Boolean>()).setLabel(new ResourceModel("user.list.arcfl")).setEnabled(isDba);
		form.add(chBArc);

		final CheckBox chBDba = new CheckBox("profile.dbaFl");
		chBDba.add(new PropertyValidator<Boolean>()).setLabel(new ResourceModel("user.list.dbafl")).setEnabled(isDba);
		form.add(chBDba);

		form.add(new Label("profile.correctDt"));

		final SubmitLink submitLink = new SubmitLink("sumbit-link") {

			private static final long serialVersionUID = 1L;

			@Override
			public void onSubmit() {
				super.onSubmit();
				if (isNew) {
					profileModel.getProfile().setUserGrant(userService.getGrants(profileModel.getProfile()));
					userService.createNewUser(profileModel.getProfile(), profileModel.getProfile().getUserAccount());
				} else {
					userService.saveOrUpdate(profileModel.getProfile());
				}
				if (pageCreator != null) {
					Page page = pageCreator.createPage();
					page.info(getString("column.common.action.saved"));
					setResponsePage(page);
				} else {
					Page page = new HomePage();
					page.info(getString("column.common.action.saved"));
					setResponsePage(page);
				}
			}

		};
		submitLink.setOutputMarkupId(true);
		form.add(submitLink);

		final RequiredTextField<String> tfCode = new RequiredTextField<String>("profile.code");
		tfCode.add(new PropertyValidator<String>()).setLabel(new ResourceModel("user.list.code"));
		tfCode.add(new UniqueFieldValidator<Long, UserProfile>(UserProfile_.code, userService, profile)).setLabel(new ResourceModel("user.list.code"));
		form.add(tfCode);

		final RequiredTextField<String> tfEmail = new RequiredTextField<String>("profile.userAccount.email");
		tfEmail.add(new PropertyValidator<String>()).setLabel(new ResourceModel("user.list.account.email")).setEnabled(isNew);
		tfEmail.add(EmailAddressValidator.getInstance());
		tfEmail.add(new UniqueUserEmailValidator(UserAccount_.email, profileModel.getProfile().getUserAccount())).setLabel(new ResourceModel("user.list.account.email"));

		form.add(tfEmail);

		final PasswordTextField tfPwd = new PasswordTextField("profile.userAccount.pwd");
		tfPwd.add(new PropertyValidator<String>()).setLabel(new ResourceModel("user.list.account.pwd")).setEnabled(isNew);
		tfPwd.add(new PatternValidator(PASSWORD_PATTERN_2));

		final PasswordTextField tfPwdConfirm = new PasswordTextField("passwordConfirm");
		tfPwdConfirm.setLabel(new ResourceModel("user.list.account.pwd.confirm")).setEnabled(isNew);

		WebMarkupContainer pwdContainer = new WebMarkupContainer("password-wrapper");

		pwdContainer.add(tfPwd);
		pwdContainer.add(tfPwdConfirm);
		pwdContainer.setVisible(isNew);
		form.add(pwdContainer);
		Link<Void> linkBack = new Link<Void>("back-link") {

			private static final long serialVersionUID = 1L;

			@Override
			public void onClick() {
				if (pageCreator != null) {
					setResponsePage(pageCreator.createPage());
				}
			}

		};


		form.add(new EqualPasswordInputValidator(tfPwd, tfPwdConfirm));
		form.setEnabled(action.equals(ActionType.EDIT));

		add(form);
		add(linkBack.setVisible(pageCreator != null));

	}

}
